import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { MenuItem } from '@/types'
import { useAuthStore } from './auth'

export const useMenuStore = defineStore('menu', () => {
  // 状态
  const menus = ref<MenuItem[]>([])
  const activeMenu = ref<string>('')
  const openKeys = ref<string[]>([])
  const collapsed = ref(false)

  // 计算属性
  const visibleMenus = computed(() => {
    const authStore = useAuthStore()
    const filteredMenus = filterMenusByPermission(menus.value, authStore.permissions)
    
    // 调试信息
    console.log('菜单权限过滤:', {
      userPermissions: authStore.permissions,
      originalMenus: menus.value,
      filteredMenus: filteredMenus
    })
    
    return filteredMenus
  })

  /**
   * 根据权限过滤菜单
   */
  const filterMenusByPermission = (menuList: MenuItem[], userPermissions: string[]): MenuItem[] => {
    return menuList.filter(menu => {
      // 检查当前菜单权限
      const hasPermission = userPermissions.includes('*') || 
        menu.permissions.length === 0 || 
        menu.permissions.some(permission => userPermissions.includes(permission))
      
      if (!hasPermission) return false
      
      // 递归过滤子菜单
      if (menu.children && menu.children.length > 0) {
        const filteredChildren = filterMenusByPermission(menu.children, userPermissions)
        // 如果有子菜单通过权限检查，则保留父菜单
        if (filteredChildren.length > 0) {
          menu.children = filteredChildren
          return true
        } else {
          // 如果所有子菜单都没有权限，则隐藏父菜单
          return false
        }
      }
      
      return true
    })
  }

  /**
   * 生成路由配置
   */
  const generateRoutes = (menuList: MenuItem[]): any[] => {
    return menuList.map(menu => ({
      path: menu.path,
      name: menu.name,
      component: menu.component ? () => import(`@/views/${menu.component}.vue`) : undefined,
      meta: {
        title: menu.name,
        icon: menu.icon,
        hidden: menu.hidden,
        permissions: menu.permissions
      },
      children: menu.children ? generateRoutes(menu.children) : undefined
    }))
  }

  /**
   * 初始化菜单数据
   */
  const initMenus = async (): Promise<void> => {
    // 模拟菜单数据 - 使用与auth.ts中一致的权限字符串
    const mockMenus: MenuItem[] = [
      {
        id: 2,
        name: '视频监控',
        path: '/video',
        icon: 'VideoCamera',
        component: undefined,
        parentId: undefined,
        sort: 1,
        permissions: [], // 父级菜单不需要权限检查
        hidden: false,
        children: [
          {
            id: 21,
            name: '实时预览',
            path: '/video/live',
            icon: 'VideoPlay',
            component: 'VideoLiveView',
            parentId: 2,
            sort: 1,
            permissions: ['preview'], // 与auth.ts中的权限字符串一致
            hidden: false
          },
          {
            id: 22,
            name: '电子地图',
            path: '/video/map',
            icon: 'MapLocation',
            component: 'MapView',
            parentId: 2,
            sort: 2,
            permissions: ['map'], // 与auth.ts中的权限字符串一致
            hidden: false
          },
          {
            id: 23,
            name: '摄像机设置',
            path: '/video/camera',
            icon: 'Camera',
            component: 'CameraView',
            parentId: 2,
            sort: 3,
            permissions: ['camera-set'], // 与auth.ts中的权限字符串一致
            hidden: false
          },
          {
            id: 24,
            name: '录像回放',
            path: '/video/playback',
            icon: 'VideoPause',
            component: 'VideoPlaybackView',
            parentId: 2,
            sort: 4,
            permissions: ['video-replay'], // 与auth.ts中的权限字符串一致
            hidden: false
          }
        ]
      },
      {
        id: 3,
        name: '报警系统',
        path: '/alarm',
        icon: 'Bell',
        component: 'AlarmView',
        parentId: undefined,
        sort: 2,
        permissions: ['alarm'], // 需要报警管理权限
        hidden: false
      },
      {
        id: 4,
        name: '系统管理',
        path: '/system',
        icon: 'Setting',
        component: undefined,
        parentId: undefined,
        sort: 3,
        permissions: [], // 父级菜单不需要权限检查
        hidden: false,
        children: [
          {
            id: 43,
            name: '用户管理',
            path: '/system/user',
            icon: 'User',
            component: 'UserView',
            parentId: 4,
            sort: 3,
            permissions: ['user'], // 需要用户管理权限
            hidden: false
          },
          {
            id: 44,
            name: '角色管理',
            path: '/system/role',
            icon: 'UserFilled',
            component: 'RoleView',
            parentId: 4,
            sort: 4,
            permissions: ['role'], // 与auth.ts中的权限字符串一致
            hidden: false
          }
        ]
      },
      {
        id: 5,
        name: '设备管理',
        path: '/device',
        icon: 'Monitor',
        component: undefined,
        parentId: undefined,
        sort: 4,
        permissions: [], // 父级菜单不需要权限检查
        hidden: false,
        children: [
          {
            id: 51,
            name: '流媒体管理',
            path: '/device/stream',
            icon: 'VideoCamera',
            component: 'StreamManageView',
            parentId: 5,
            sort: 1,
            permissions: ['nvr'], // 与auth.ts中的权限字符串一致
            hidden: false
          },
          {
            id: 52,
            name: 'NMC管理',
            path: '/device/nmc',
            icon: 'Setting',
            component: 'NMCManageView',
            parentId: 5,
            sort: 2,
            permissions: ['nmc'], // 与auth.ts中的权限字符串一致
            hidden: false
          }
        ]
      }
    ]

    menus.value = mockMenus

    // 正式环境请使用实际API
    // const response = await getMenuList()
    // menus.value = response.data
  }

  /**
   * 设置当前激活菜单
   */
  const setActiveMenu = (menuPath: string): void => {
    activeMenu.value = menuPath
  }

  /**
   * 切换菜单折叠状态
   */
  const toggleCollapsed = (): void => {
    collapsed.value = !collapsed.value
  }

  /**
   * 设置展开的菜单键
   */
  const setOpenKeys = (keys: string[]): void => {
    openKeys.value = keys
  }

  /**
   * 根据路径查找菜单项
   */
  const findMenuByPath = (path: string, menuList = menus.value): MenuItem | null => {
    for (const menu of menuList) {
      if (menu.path === path) {
        return menu
      }
      if (menu.children) {
        const found = findMenuByPath(path, menu.children)
        if (found) return found
      }
    }
    return null
  }

  /**
   * 获取面包屑导航
   */
  const getBreadcrumb = (path: string): MenuItem[] => {
    const breadcrumb: MenuItem[] = []
    
    const findPath = (menuList: MenuItem[], targetPath: string, parents: MenuItem[] = []): boolean => {
      for (const menu of menuList) {
        const currentPath = [...parents, menu]
        
        if (menu.path === targetPath) {
          breadcrumb.push(...currentPath)
          return true
        }
        
        if (menu.children && findPath(menu.children, targetPath, currentPath)) {
          return true
        }
      }
      return false
    }
    
    findPath(menus.value, path)
    return breadcrumb
  }

  return {
    // 状态
    menus,
    activeMenu,
    openKeys,
    collapsed,
    
    // 计算属性
    visibleMenus,
    
    // 方法
    initMenus,
    setActiveMenu,
    toggleCollapsed,
    setOpenKeys,
    findMenuByPath,
    getBreadcrumb,
    generateRoutes
  }
})